package com.game.connection.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.game.connection.message.Message;

/**
 * 
 */

/**
 * @author gustavo
 * 
 */
public class ServerPlayerLister implements Runnable {

	private Integer playerId;

	private HashMap<Integer, List<Message>> messages;

	private BufferedReader in;

	public ServerPlayerLister(Integer id, InputStream inPutStream,
			HashMap<Integer, List<Message>> message) {

		playerId = id;
		messages = message;
		in = new BufferedReader(new InputStreamReader(inPutStream));
	}

	public void receive() throws IOException {
		String msg = in.readLine();
		if (msg != null && msg.trim().length() > 6) {
			Message msgt = new Message(playerId, msg);
			Set<Integer> keys = messages.keySet();
			for (Integer id : keys) {
				if (id != playerId) {
					messages.get(id).add(msgt);
				}
			}
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				receive();
				synchronized (this.messages) {
					this.messages.notifyAll();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
